package com.qili.util;

import net.sf.jxls.transformer.XLSTransformer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhaoyongke
 * @date 2021/5/10
 * @description
 */
public class ExcelExportUtil {
    /**
    * @Author:zhaoyongke
    * @Description: Excel 根据模板导出Excel
    * @param response
    * @param dataMap
    * @param fileName 文件名称
     *@param fp_id base_pathconfig表主键
    * @Date:14:34 2021/5/10
    */
    public static void exportExcel(HttpServletResponse response,HashMap dataMap,String fileName,String  fp_id)  throws IOException {
        try {
            // 获取模板信息
            String srcFilePath = FilePathUtil.getPathConfigTemplateFile(fp_id);
            response.reset();
            response.setContentType("application" + File.separator + "vnd.ms-excel");   //下载文版类型
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
            //生成的临时导出文件
            File destFile = File.createTempFile(fileName, ".xls");
            //  开始转换。利用  transformer 转到Excel
            XLSTransformer transformer = new XLSTransformer();
            // 参数：srcFilePath：模板源文件    cMap：需要导出的数据   destFile.getAbsolutePath()：下载的目标文件
            transformer.transformXLS(srcFilePath, dataMap, destFile.getAbsolutePath());

            FileInputStream fis = new FileInputStream(destFile);
            OutputStream out = response.getOutputStream();
            byte[] bytes = new byte[512];
            int i = 0;
            while ((i = fis.read(bytes)) != -1) {
                out.write(bytes, 0, i);
            }
            out.close();
            fis.close();
            destFile.delete();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }




}
